import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: LeetCode
 * @description: LeetCode : 剑指 Offer II 075. 数组相对排序
 * @author: WXY
 * @create: 2023-01-01 14:16
 * @Version 1.0
 **/
public class Num_offer2_075_relativeSortArray {
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr2.length; i++) {
            map.put(arr2[i], i);
        }
        int max = arr2.length;
        var cmp = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                if (map.containsKey(o1) && map.containsKey(o2)) {
                    return map.get(o1) - map.get(o2);
                }
                if (map.containsKey(o1)) {
                    return -1;
                } else if (map.containsKey(o2)) {
                    return 1;
                } else {
                    return o1 - o2;
                }
            }
        };
        List<Integer> list = Arrays.stream(arr1).boxed().collect(Collectors.toList());
        list.sort(cmp);
        return list.stream().mapToInt(Integer::valueOf).toArray();
    }

}
